package com.alibaba.cloud.exception.handler;

import java.util.Objects;

import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.alibaba.cloud.enums.ResultCodeEnum;
import com.alibaba.cloud.exception.BaseException;
import com.alibaba.cloud.exception.BusinessException;
import com.alibaba.cloud.exception.MessageException;
import com.alibaba.cloud.exception.ServerException;
import com.alibaba.cloud.utils.ResultVo;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description:全局异常处理
 * @author: zhb1316783262@163.com
 * @date: 2019年4月28日下午7:18:54
 */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * @date: 2020/5/19 10:26
	 * @description: 前置异常处理(进入controller 前可能出现的异常)
	 * @author: zhb1316783262@163.com
	 */
	@ExceptionHandler({ NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class,
			HttpMediaTypeNotSupportedException.class, MissingPathVariableException.class,
			MissingServletRequestParameterException.class, TypeMismatchException.class,
			HttpMessageNotReadableException.class, HttpMessageNotWritableException.class,
			HttpMediaTypeNotAcceptableException.class, ServletRequestBindingException.class,
			ConversionNotSupportedException.class, MissingServletRequestPartException.class,
			AsyncRequestTimeoutException.class })
	public ResultVo<String> handleServletException(Exception ex) {
		log.error("[GlobalExceptionHandler][handleServletException] 请求失败exception", ex);
		return ResultVo.paramError(ResultCodeEnum.PARAMETER_ERROR, ex.getMessage());
	}

	/**
	 * @Description: 参数绑定异常
	 * @Author: zhb1316783262@163.com
	 * @Date: 2020年5月19日上午11:24:52
	 */
	@ExceptionHandler(value = BindException.class)
	public ResultVo<String> handleBindException(BindException ex) {
		log.error("[GlobalExceptionHandler][handleBindException] 参数绑定校验exception", ex);
		return wrapperBindingResult(ex.getBindingResult());
	}

	/**
	 * @Description: 参数校验异常，将校验失败的所有异常组合成一条错误信息
	 * @Author: zhb1316783262@163.com
	 * @Date: 2020年5月19日上午11:24:34
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public ResultVo<String> handleValidException(MethodArgumentNotValidException ex) {
		log.error("[GlobalExceptionHandler][handleValidException] 参数校验exception", ex);
		return wrapperBindingResult(ex.getBindingResult());
	}

	/**
	 * @Description: bindingResult 结果处理
	 * @Author: zhb1316783262@163.com
	 * @Date: 2020年5月19日上午11:23:43
	 */
	private ResultVo<String> wrapperBindingResult(BindingResult bindingResult) {
		StringBuilder msg = new StringBuilder();
		for (ObjectError error : bindingResult.getAllErrors()) {
			msg.append(", ");
			if (error instanceof FieldError) {
				msg.append(((FieldError) error).getField()).append(": ");
			}
			msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());

		}
		return ResultVo.paramError(null, msg.substring(2));
	}

	/**
	 * @date: 2020/5/19 17:24
	 * @description: 业务异常处理
	 * @author: zhb1316783262@163.com
	 */
	@ExceptionHandler(value = { BusinessException.class })
	public ResultVo<String> businessExceptionHandler(BusinessException e) {
		log.error("[GlobalExceptionHandler][businessExceptionHandler] 业务exception", e);
		if (Objects.nonNull(e.getCodeEnum())) {
			return ResultVo.common(e.getCodeEnum(), null, e.getMessage());
		}
		return ResultVo.error("未知业务异常");
	}

	/**
	 * @date: 2020/5/19 17:24
	 * @description: 通用自定义异常处理
	 * @author: zhb1316783262@163.com
	 */
	@ExceptionHandler(value = { BaseException.class })
	public ResultVo<String> commonHandler(BaseException e) {
		log.error("[GlobalExceptionHandler][commonHandler] 服务exception", e);
		if (Objects.nonNull(e.getResultCodeEnum())) {
			return ResultVo.common(e.getResultCodeEnum(), null, e.getMessage());
		}
		if (e instanceof ServerException) {
			return ResultVo.error(null, "未知锁异常");
		}
		return ResultVo.error(null, "未知系统异常");
	}

	/***
	 * @description: 信息发送失败记录
	 * @author: zhb1316783262@163.com
	 * @date: 2022/6/25 15:22
	 */
	@ExceptionHandler(value = { MessageException.class })
	public ResultVo<String> messageSendExceptionHandler(BusinessException e) {
		log.error("[GlobalExceptionHandler][messageExceptionHandler] 信息发送exception", e);
		if (Objects.nonNull(e.getCodeEnum())) {
			return ResultVo.common(e.getCodeEnum(), null, e.getMessage());
		}
		return ResultVo.error("信息发送异常");
	}

	/**
	 * @Description: 其他未知异常
	 * @Author: zhb1316783262@163.com
	 * @Date: 2020年5月19日上午11:22:43
	 */
	@ExceptionHandler(value = { Exception.class })
	public ResultVo<String> exceptionHandler(Exception e) {
		log.error("[GlobalExceptionHandler][exceptionHandler] 其他未知exception", e);
		return ResultVo.error("未知异常");
	}
}
